<?php
namespace Pig\Controller;
use \Pig\Util\Page;

class ImageController extends BaseController {
    public $tca = array();
    public $tbName = CONTROLLER_NAME;
    public $image_path = '';

    /**
     * 高级搜索
     + 数据说明
     + label    页面显示数据
     + name     数据库字段名
     + type     搜索类型(目前只支持input及select的搜索)
     + data     select框所有数据(在init函数中赋值,input类型,此项为空)
     + value    接收页面传值并在搜索之后在页面展示
     + category 针对input的类型(normal代表普通的input,time代表时间搜索的input),select类型无此数据
     */
    public $search = array(
    );

    /**
     * 数据操作(权限管理)
     + 数据说明(目前只支持添加,数据导入,数据导出----注意方法名需保持跟权限表的添加的数据一致)
     + label     页面显示操作权限
     + access    操作方法
     + class     页面显示样式
     */
    public $action = array(
        array('label' => '添加', 'access' => 'save', 'class' => 'icon-plus')
    );

    /**
     * 管理操作(权限管理)
     + 数据说明(注意方法名需保持跟权限表的添加的数据一致)
     + label     页面显示操作权限
     + access    操作方法
     */
    public $edit_action = array(
        array('label' => '编辑', 'access' => 'edit', 'class' => 'btn green-stripe mini','type' => 'link'),
        array('label' => '删除', 'access' => 'del', 'class' => 'btn red-stripe mini del', 'type' => 'link'),
    );

    /**
     * 操作管理(数据删除,发布,草稿,置顶,不顶,热门,不热等操作)
     + 数据说明(确保数据表中有相关参数,若需要添加特殊操作,应先在BaseController下添加相关操作方法)
     + label     页面显示操作内容
     + access    操作方法
     */
    public $handle = array(
    );

    /**
     * 列表页表头展示内容
     + 数据说明(确保数据表中有相关参数,若需要添加特殊操作,应先在BaseController下添加相关操作方法)
     + label     页面显示操作内容
     + field     字段名
     + status    编辑状态(true为列表页可编辑,false为不能编辑)
     */
    public $index_content = array(
        array('label' => 'ID编号', 'field' => 'id', 'status' => false),
        array('label' => '图片', 'field' => 'image', 'status' => false),
        array('label' => '描述', 'field' => 'remark', 'status' => false),
    );

    protected function init() {
        //高级筛选
        $this->assign('status_all', $this->status_all);

        //数据操作(权限管理)
        $this->assign('action', $this->action);

        //管理操作
        $this->assign('edit_action', $this->edit_action);

        //操作管理
        $this->assign('handle', $this->handle);

        //列表页表头展示内容
        $this->assign('index_content', $this->index_content);
        $info = '';
        if (ACTION_NAME == 'edit') {
            $id = I('param.id');
            $info = M($this->tbName)->where('id = ' . $id)->find();
            //图片路径
            $this->image_path = CONTROLLER_NAME . '/';
        }
        $data = M('image_category')->where(array('deleted' => 0))->Field('id as "0",name as "1"')->select();
        $categories = '';
        foreach ($data as $key => $value) {
             $selected = $value[0] == $info['category_id']?'selected="selected"':'';
             $categories .= '<option value="'.$value[0].'" '.$selected.' >'.$value[1].'</option>';
         } 
        //配置字段
        $this->tca = array(
            'category_id' => array(
                'label' => '图片分类',
                'type' => 'select_tree',
                'data' => $categories,
                'required' => true
            ),
            'image' => array(
                'label' => '图片',
                'type' => 'image',
                'name' => 'image',
                'required' => true
            ),
            'remark' => array(
                'label' => '描述',
                'type' => 'textarea',
            )
        );
    }

    /**
     * 列表页面
     */
    public function index() {
        $this->init(); //加载初始化数据
        $Obj = D($this->tbName); //实例化对象

        $Where = "deleted=0";
        
        if(I('post.limit_num') != ''){
            session('page_limit_num', I('post.limit_num'));
        }
        $sorting = I('get.sorting') ? I('get.sorting') : 'id';
        $order = I('get.order') ? I('get.order') : 'desc';
        $limit_num = $_SESSION['page_limit_num'] ? $_SESSION['page_limit_num'] : 10;
        
        $Page = new Page($Obj->where($Where)->count(), $limit_num); // 实例化分页类 传入总记录数和每页显示的记录数
        $list = $Obj->where($Where)->order($sorting . ' ' . $order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        if($list && array_key_exists('image', $list[0])){
            foreach ($list as $key => &$value) {
                $value['image'] = C('PATH_UPLOAD').CONTROLLER_NAME.'/'.$value['image'];
            }
        }
        $this->assign('list', $list); // 赋值数据集
        $this->assign('page', $Page->show()); // 分页显示输出 
        $this->display(); // 输出模板
    }

    /**
     * 编辑数据
     */
    public function edit() {
        $this->save();
    }
    /**
     * 保存数据
     */
    public function save() {
        try{
            $this->init();
            //编辑数据
            $id = I('request.id') ? I('request.id') : null;
            $info = M($this->tbName)->where('id = ' . $id)->find();
            if (IS_POST) {
                foreach ($_POST as $key => $val) {
                    if(@$this->tca[$key]['required'] && !preg_match('/\S/', $val)){
                        $this->error($this->tca[$key]['label'] . '*是必填项!');
                    }
                }
                //删除文件 begin **********************************
                $path = $this->Config['path_upload'] . CONTROLLER_NAME . '/';
                $save_path = ''; // 设置附件上传目录
                $extent_path =  '';
                if ($info && $info['image'] && $_POST['delete_image'] == '1') {
                    $file_path = $path.$save_path.$extent_path;
                    $this->delInfoFile($file_path, $info['image']);
                } else {
                    unset($_POST['image']);
                }
                //删除文件 end **********************************
                
                //文件上传 begin **********************************
                if (count($_FILES) && isset($_FILES['image'])) {
                    $thumb_width = '';
                    $thumb_height = '';
                    $upload = $this->uploadFile('image', $path, $save_path, $extent_path, $thumb_width, $thumb_height);

                    if (is_array($upload) && $upload['upload']) {
                        $_POST['image'] = $upload['info'];
                    } else {
                        $this->error($upload['info']);
                    }
                }
                //文件上传 end **********************************
                $Obj = D($this->tbName);
                $result = $Obj->create();
                if (!$result) {
                    $this->error($Obj->getError());
                } else {        
                    if ($id) {
                        $Obj->tstamp = time();
                        $id = $Obj->where(array('id' => $id))->save();
                        $message = '编辑成功!';
                    } else {
                        $Obj->crdate = time();
                        $Obj->tstamp = time();
                        $id = $Obj->add();
                        $message = '添加成功!';
                    }
                    if($id){
                        $this->success($message, U(CONTROLLER_NAME . '/index', 'kept=1'));
                        exit;
                    }else{
                        debug($Obj->_sql());
                        $this->error('保存失败');
                        exit;
                    }
                    
                }
            }
            //自动渲染字段
            parent::autoFields($this->tca, $info);
            $this->display('info');
        }catch(\Exception $e){
            debug($e->getmessage());
            //判断是否有文件上传
            if(count($_FILES)){
                $extent_path = '';
                $file_path = $path . $extent_path;
                if(is_file($file_path.$upload['info'])){
                    $this->delInfoFile($file_path, $upload['info']);
                }
            }
            $message = IS_AJAX?'保存失败':'';
            $this->error($message);
        }
    }
}

?>